package com.canyou.system;

import com.canyou.api.BaseApiController;
import com.canyou.api.ResponseBO;
import com.canyou.constants.CommonConstants;
import com.canyou.constants.MsgConstants;
import com.canyou.system.entity.dept.DeptDTO;
import com.canyou.system.entity.dept.DeptVO;
import com.canyou.system.model.Dept;
import com.canyou.system.service.DeptService;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

import static com.canyou.api.ResponseBO.*;

/**
 * 部门管理前端控制器
 *
 * @author canyou
 * @since 2019-05-14
 */
@Api(tags = "部门管理")
@ApiSort(1004)
@RestController
@RequestMapping("/dept")
@Validated
public class DeptController extends BaseApiController {

    @Autowired
    private DeptService deptService;

    @ApiOperation(value = "获取部门树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptName", paramType = "query", value = "部门名称", dataType = "string", example = "测试部门"),
            @ApiImplicitParam(name = "orgName", paramType = "query", value = "机构名称", dataType = "string", example = "测试机构")
    })
    @PreAuthorize("hasPerm('dept')")
    @GetMapping("/get_list")
    public ResponseBO<List<DeptVO>> listDept(@RequestParam(required = false) String deptName,
                                             @RequestParam(required = false) String orgName) {
        List<DeptVO> deptTree = deptService.getDeptTree(deptName, orgName);
        return ok(deptTree);
    }

    @ApiOperation(value = "根据id获取部门详情")
    @ApiImplicitParam(name = "id", paramType = "query", value = "部门id", dataType = "int", required = true, example = "1")
    @PreAuthorize("hasPerm('dept')")
    @GetMapping("/get_info")
    public ResponseBO<DeptVO> getDept(@NotNull(message = "部门id不能为空")
                                      @RequestParam(required = false) Long id) {
        return ok(deptService.getDeptDetailById(id));
    }

    @ApiOperation(value = "新增编辑部门")
    @PreAuthorize("hasPerm('dept:add','dept:edit') ")
    @PostMapping("/save")
    public ResponseBO saveDept(@ApiParam(name = "deptDTO", type = "DeptDTO", value = "部门新增编辑数据", required = true)
                               @Valid
                               @NotNull(message = "角色信息不能为空")
                               @RequestBody DeptDTO deptDTO) {
        Long deptId = deptDTO.getId();
        Long parentId = deptDTO.getParentId();
        if (deptService.existDept(deptDTO.getOrgId(), deptDTO.getDeptName(), deptId)) {
            return illegal("部门名已存在");
        }
        Dept dept = new Dept();
        if (deptId != null) {
            dept = deptService.getById(deptId);
            if (dept == null) {
                return illegal("deptId: " + deptId + "对应的部门不存在");
            }
            if (deptId.equals(parentId)) {
                return illegal("父部门不能是本部门");
            }
        }
        // 父部门所属机构与当前部门所属机构必须一致
        if (!CommonConstants.DEFAULT_PARENT_ID.equals(parentId)) {
            Dept parentDept = deptService.getById(parentId);
            if (parentDept == null) {
                return illegal("parentId: " + parentId + "对应的父部门不存在");
            }
            if (!deptDTO.getOrgId().equals(parentDept.getOrgId())) {
                return illegal("父部门与当前部门所属机构不一致");
            }
        }
        BeanUtils.copyProperties(deptDTO, dept);
        boolean isSuccess = deptService.saveOrUpdate(dept);
        return result(isSuccess, deptId);
    }

    @ApiOperation(value = "删除部门")
    @PreAuthorize("hasPerm('dept:del')")
    @PostMapping("/remove")
    public ResponseBO removeDept(@ApiParam(name = "id", type = "Long", value = "部门id", required = true, example = "1")
                                 @Valid
                                 @NotNull(message = "部门id不能为空")
                                 @RequestBody Long id) {
        if (deptService.getDeptChildCount(id) > 0) {
            return illegal("该部门存在子部门, 无法删除");
        }
        if (deptService.getDeptUserCount(id) > 0) {
            return illegal("该部门被用户使用, 无法删除");
        }
        return ok(deptService.removeById(id), MsgConstants.DEL_SUCCESS);
    }

}
